import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../../services/auth_service.dart';
import '../../services/database_service.dart';
import '../../services/minio_service.dart';
import '../../models/file_item.dart';
import '../../widgets/file_list_item.dart';
import '../../widgets/upload_button.dart';
import '../auth/login_screen.dart';
import 'file_detail_screen.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  String? _currentPath;
  List<FileItem> _files = [];
  bool _isLoading = true;
  final TextEditingController _searchController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _loadFiles();
  }

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }

  Future<void> _loadFiles() async {
    setState(() => _isLoading = true);
    
    final authService = Provider.of<AuthService>(context, listen: false);
    final databaseService = Provider.of<DatabaseService>(context, listen: false);
    
    if (authService.currentUser != null) {
      final files = await databaseService.getFilesByUserId(
        authService.currentUser!.id!,
        parentPath: _currentPath,
      );
      setState(() {
        _files = files;
        _isLoading = false;
      });
    }
  }

  Future<void> _navigateToFolder(FileItem folder) async {
    setState(() {
      _currentPath = folder.path;
    });
    await _loadFiles();
  }

  Future<void> _navigateUp() async {
    if (_currentPath != null) {
      final parts = _currentPath!.split('/');
      if (parts.length > 1) {
        parts.removeLast();
        setState(() {
          _currentPath = parts.join('/');
        });
      } else {
        setState(() {
          _currentPath = null;
        });
      }
      await _loadFiles();
    }
  }

  Future<void> _createFolder() async {
    final result = await showDialog<String>(
      context: context,
      builder: (context) => _CreateFolderDialog(),
    );
    
    if (result != null && result.isNotEmpty) {
      final authService = Provider.of<AuthService>(context, listen: false);
      final databaseService = Provider.of<DatabaseService>(context, listen: false);
      
      final folderPath = _currentPath != null ? '$_currentPath/$result' : result;
      
      await databaseService.createFolder(
        result,
        folderPath,
        authService.currentUser!.id!,
        parentPath: _currentPath,
      );
      
      await _loadFiles();
    }
  }

  Future<void> _deleteFile(FileItem file) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认删除'),
        content: Text('确定要删除 "${file.name}" 吗？'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Navigator.pop(context, true),
            child: const Text('删除', style: TextStyle(color: Colors.red)),
          ),
        ],
      ),
    );

    if (confirmed == true) {
      final databaseService = Provider.of<DatabaseService>(context, listen: false);
      final minioService = Provider.of<MinioService>(context, listen: false);
      
      // Delete from MinIO if it's a file (not folder)
      if (!file.isFolder && file.minioObjectName.isNotEmpty) {
        try {
          await minioService.deleteFile(file.minioObjectName);
        } catch (e) {
          debugPrint('Error deleting from MinIO: $e');
        }
      }
      
      // Delete from database
      await databaseService.deleteFile(file.id!);
      await _loadFiles();
      
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(content: Text('已删除 "${file.name}"')),
        );
      }
    }
  }

  Future<void> _logout() async {
    final authService = Provider.of<AuthService>(context, listen: false);
    await authService.logout();
    
    if (mounted) {
      Navigator.of(context).pushReplacement(
        MaterialPageRoute(builder: (context) => const LoginScreen()),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    final authService = Provider.of<AuthService>(context);
    
    return Scaffold(
      appBar: AppBar(
        title: Text(_currentPath ?? '小森云盘'),
        leading: _currentPath != null 
          ? IconButton(
              icon: const Icon(Icons.arrow_back),
              onPressed: _navigateUp,
            )
          : null,
        actions: [
          IconButton(
            icon: const Icon(Icons.search),
            onPressed: () {
              showSearch(
                context: context,
                delegate: _FileSearchDelegate(_files),
              );
            },
          ),
          PopupMenuButton(
            itemBuilder: (context) => [
              PopupMenuItem(
                child: const Row(
                  children: [
                    Icon(Icons.person),
                    SizedBox(width: 8),
                    Text('个人信息'),
                  ],
                ),
                onTap: () {
                  // TODO: Navigate to profile screen
                },
              ),
              PopupMenuItem(
                child: const Row(
                  children: [
                    Icon(Icons.logout),
                    SizedBox(width: 8),
                    Text('退出登录'),
                  ],
                ),
                onTap: _logout,
              ),
            ],
          ),
        ],
      ),
      body: Column(
        children: [
          // User info bar
          Container(
            width: double.infinity,
            padding: const EdgeInsets.all(16),
            color: Theme.of(context).colorScheme.surface,
            child: Row(
              children: [
                CircleAvatar(
                  backgroundColor: Theme.of(context).colorScheme.primary,
                  child: Text(
                    authService.currentUser?.username.characters.first.toUpperCase() ?? 'U',
                    style: const TextStyle(color: Colors.white, fontWeight: FontWeight.bold),
                  ),
                ),
                const SizedBox(width: 12),
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '欢迎，${authService.currentUser?.username ?? 'User'}',
                      style: Theme.of(context).textTheme.titleMedium?.copyWith(
                        fontWeight: FontWeight.w600,
                      ),
                    ),
                    Text(
                      '共 ${_files.length} 个项目',
                      style: Theme.of(context).textTheme.bodySmall?.copyWith(
                        color: Colors.grey[600],
                      ),
                    ),
                  ],
                ),
              ],
            ),
          ),
          
          // File list
          Expanded(
            child: _isLoading
              ? const Center(child: CircularProgressIndicator())
              : _files.isEmpty
                  ? Center(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Icon(
                            Icons.folder_open,
                            size: 64,
                            color: Colors.grey[400],
                          ),
                          const SizedBox(height: 16),
                          Text(
                            '这里还没有文件',
                            style: TextStyle(
                              fontSize: 18,
                              color: Colors.grey[600],
                            ),
                          ),
                          const SizedBox(height: 8),
                          Text(
                            '点击右下角的按钮开始上传',
                            style: TextStyle(
                              color: Colors.grey[500],
                            ),
                          ),
                        ],
                      ),
                    )
                  : RefreshIndicator(
                      onRefresh: _loadFiles,
                      child: ListView.builder(
                        itemCount: _files.length,
                        itemBuilder: (context, index) {
                          final file = _files[index];
                          return FileListItem(
                            file: file,
                            onTap: () {
                              if (file.isFolder) {
                                _navigateToFolder(file);
                              } else {
                                Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                    builder: (context) => FileDetailScreen(file: file),
                                  ),
                                );
                              }
                            },
                            onDelete: () => _deleteFile(file),
                          );
                        },
                      ),
                    ),
          ),
        ],
      ),
      floatingActionButton: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          FloatingActionButton(
            heroTag: 'create_folder',
            onPressed: _createFolder,
            backgroundColor: Colors.grey[700],
            child: const Icon(Icons.create_new_folder),
          ),
          const SizedBox(height: 16),
          UploadButton(
            currentPath: _currentPath,
            onUploadComplete: _loadFiles,
          ),
        ],
      ),
    );
  }
}

class _CreateFolderDialog extends StatefulWidget {
  @override
  State<_CreateFolderDialog> createState() => _CreateFolderDialogState();
}

class _CreateFolderDialogState extends State<_CreateFolderDialog> {
  final _controller = TextEditingController();

  @override
  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Text('创建文件夹'),
      content: TextField(
        controller: _controller,
        decoration: const InputDecoration(
          labelText: '文件夹名称',
          hintText: '输入文件夹名称',
        ),
        autofocus: true,
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.pop(context),
          child: const Text('取消'),
        ),
        TextButton(
          onPressed: () => Navigator.pop(context, _controller.text.trim()),
          child: const Text('创建'),
        ),
      ],
    );
  }
}

class _FileSearchDelegate extends SearchDelegate<FileItem?> {
  final List<FileItem> files;

  _FileSearchDelegate(this.files);

  @override
  List<Widget> buildActions(BuildContext context) {
    return [
      IconButton(
        icon: const Icon(Icons.clear),
        onPressed: () => query = '',
      ),
    ];
  }

  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
      icon: const Icon(Icons.arrow_back),
      onPressed: () => close(context, null),
    );
  }

  @override
  Widget buildResults(BuildContext context) {
    return buildSuggestions(context);
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    final results = files.where((file) =>
      file.name.toLowerCase().contains(query.toLowerCase())
    ).toList();

    return ListView.builder(
      itemCount: results.length,
      itemBuilder: (context, index) {
        final file = results[index];
        return FileListItem(
          file: file,
          onTap: () => close(context, file),
          onDelete: () {},
        );
      },
    );
  }
}